from pymongo import MongoClient
from pymongo.collection import ReturnDocument

class MongoConnector:
    def __init__(self, dbname='test', host='localhost', port=27017):
        """

        :param dbname: 默认test
        :param host: 默认本地 localhost ， 腾讯云是公网ip
        :param port: 默认27017
        """
        self.client = MongoClient(host, port)
        self.db = self.client[dbname]

    def create_one(self, collection_name, data):
        """
        插入一条数据
        :param collection_name:
        :param data:
        :return:
        """
        collection = self.db[collection_name]
        return collection.insert_one(data).inserted_id

    def read_one(self, collection_name, query):
        """
        读取一条数据
        :param collection_name:
        :param query:
        :return:
        """
        collection = self.db[collection_name]
        return collection.find_one(query)

    def read_many(self, collection_name, query=None):
        """
        读取多条数据
        :param collection_name:
        :param query:
        :return:
        """
        collection = self.db[collection_name]
        return list(collection.find(query))

    def update_one(self, collection_name, filter_query, update_data):
        """
        更新一条数据
        :param collection_name:
        :param filter_query:
        :param update_data:
        :return:
        """
        collection = self.db[collection_name]
        res = collection.update_one(
            filter_query,
            {'$set': update_data}

        )

        return res

    def delete_one(self, collection_name, query):
        """
        删除一条数据
        :param collection_name:
        :param query:
        :return:
        """
        collection = self.db[collection_name]
        return collection.delete_one(query)

# 使用示例
if __name__ == "__main__":
    # 初始化 MongoClient
    client = MongoConnector()

    # # 创建数据
    # insert_id = client.create_one('users', {'name': 'John Doe', 'age': 30})
    # print(f'Inserted ID: {insert_id}')
    #
    # # 读取单个数据
    # user = client.read_one('users', {'name': 'John Doe'})
    # print(f'User: {user}')
    #
    # # 读取多个数据
    users = client.read_many('users')
    print(f'Users: {users}')
    #
    # # 更新数据
    # updated_user = client.update_one('users', {'name': 'John Doe'},{'age': 31})
    # print(f'Updated User: {updated_user}')

    # 删除数据
    delete_result = client.delete_one('users', {'name': 'John Doe'})
    print(f'Delete Result: {delete_result.deleted_count}')